<template>
  <div class="box">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 大卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input @clear="getUserlist" clearable @keydown.native.enter="getUserlist" v-model="queryInfo.query"  placeholder="请输入内容">
            <el-button icon="el-icon-search" slot="append" @click="getUserlist">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 管理员列表 -->
      <el-table border :data="userList" stripe style="width: 100%">
        <el-table-column label="#" type="index">
        </el-table-column>
        <el-table-column 
          prop="username" 
          label="姓名" 
          min-width>
        </el-table-column>
        <el-table-column 
          prop="email" 
          label="邮箱" 
          min-width>
        </el-table-column>
        <el-table-column 
          prop="mobile" 
          label="电话">
        </el-table-column>
        <el-table-column 
          prop="role_name" 
          label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <!-- 在table-column列中使用template标签可通过作用域插槽获得一个变量，该变量 -->
          <!-- 账号状态 -->
          <template scope="{row}">
            <el-switch v-model="row.mg_state" @change="switchState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="174px">
          <template scope="{row}">
            <!-- 编辑账号 -->
            <el-button 
            type="primary" icon="el-icon-edit" 
            size="mini"
            @click="addDialogVisibleEdit(row)"
            ></el-button>
            <!-- 删除账号 -->
            <el-button 
            type="danger" icon="el-icon-delete" size="mini"
            @click="delUser(row)"
            ></el-button>
            <!-- 分配角色通过tooltip包裹了一下，将会hover后提示文字分配角色，enterable指是否允许进入提示信息框内 -->
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 点击添加用户提示对话框 -->
    <el-dialog 
      :modal-append-to-body="false"
      title="创建用户"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogReset"
      :close-on-click-modal="false"
      >
      <!-- 内容主体区 -->
      <el-form 
      :model="formData" 
      label-width="100px"
      :rules="formDataRules"
      ref="addFormRef"
      >
        <el-form-item 
        prop="username" 
        required 
        label="用户名" 
        label-width="auto">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" required label="密码" label-width="auto">
          <el-input type="password"  v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" required label="邮箱" label-width="auto">
          <el-input type="email" v-model="formData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="tel" required label="手机" label-width="auto">
          <el-input type="tel" v-model="formData.tel" autocomplete="off">   
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户_dialog对话框 -->
    <el-dialog 
      title="修改用户信息" 
      :visible.sync="isdialogVisible"
      :modal-append-to-body="false"
      >
      <el-form 
      :model="editFormData"
      ref="editForm"
      :rules="editFormRule"
      label-width="100px"
      >
        <!-- 修改用户_用户名表单，禁止修改 -->
        <el-form-item 
        label="用户名" 
        >
          <el-input 
          v-model="editFormData.username" :disabled="true"
          ></el-input>
        </el-form-item>

        <!-- 修改用户_邮箱表单 -->
        <el-form-item 
        label="邮箱" 
        prop="email"
        required 
        >
          <el-input 
          v-model="editFormData.email"
          ></el-input>
        </el-form-item>

        <!-- 修改用户_手机号表单 -->
        <el-form-item 
        label="手机" 
        prop="tel"
        required 
        >
          <el-input 
          v-model="editFormData.tel"
          ></el-input>
        </el-form-item>

      </el-form>    
        <span slot="footer">
            <el-button @click="isdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配角色diaLog对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      :modal-append-to-body="false"
      @close="setRoleDialogClose">
      <div>
        <p>当前的用户：{{this.currentUser.username}}</p>
        <p>当前的角色：{{this.currentUser.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="currentRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <div slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleCommit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱格式是否正确
    var checkEmail = (rule,value,cb)=>{
      const emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if(emailReg.test(value)){
        return cb();
      }
      return cb(new Error('请输入正确的邮箱格式'))
    }
    // 验证手机号格式是否正确
    var checkTel = (rule,value,cb)=>{
      const telReg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if(telReg.test(value)){
        return cb();
      }
      return cb(new Error('请输入正确的手机号格式'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        // 当前每页展示多少条数据
        pagesize: 5,
      },
      userList: [],
      total: 0,
      // 控制弹出框是否显示
      addDialogVisible:false,
      // diaLog中的表单验证数据
      formData:{
        username:'',
        password:'',
        email:'',
        tel:''
      },
      // 表单校验规则
      formDataRules:{
        username:[
          {
            required:true,
            message:'输入不能为空！',
            trigger:'blur',
          },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
          
        ],
        password:[
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        email:[
          { required: true, message: "请输入注册邮箱", trigger: "blur" },
          {
            validator:checkEmail,trigger:'blur'
          }
        ],
        tel:[
          { required: true, message: "请输入注册手机号", trigger: "blur" },
          {
            validator:checkTel,trigger:'blur'
          }
        ]
      },
      // 控制修改用户的dialog对话框是否展示
      isdialogVisible:false,
      // 修改用户时的表单数据
      editFormData:{
        username:this.userList,
        // 可修改邮箱
        email:'',
        // 可修改手机号
        tel:'',
        id:'',
      },
      // 修改用户的表单校验规则
      editFormRule:{
        email:[
          { required: true, message: "请输入注册邮箱", trigger: "blur" },
          {
            validator:checkEmail,trigger:'blur'
          }
        ],
        tel:[
          { required: true, message: "请输入注册手机号", trigger: "blur" },
          {
            validator:checkTel,trigger:'blur'
          }
        ]
      },
      // 控制分配角色dialog对话框显示与隐藏
      setRoleDialogVisible:false,
      // 当点击分配角色对话框时，对应的当前行用户的数据
      currentUser:{},
      // 获取所有角色列表
      rolesList:[],
      // 当前用户所选中的角色的id值
      currentRoleId:'',
    };
  },
  methods: {
    // 通过请求获取用户列表
    async getUserlist() {
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 当页码大小(多少行信息展示一页)发生改变时，触发该事件
    handleSizeChange(newSize){
      this.queryInfo.pagesize = newSize;
      this.getUserlist();
    },
    // 当前页变化时，触发该事件
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage;
      this.getUserlist();
    },
    // 点击状态切换后，请求更改数据库中的该账号状态
    // 便和数据库该账号的状态同步
    async switchState(user){
      const {data:res} = await this.$axios.put(`users/${user.id}/state/${user.mg_state}`)
      if(res.meta.status !== 200){
        return this.$message.error(res.meta.msg);
      }
      this.$message.success('更新用户状态成功');

    },
    // 监听关闭diaLog对话框时的事件
    addDialogReset(){
      // 当关闭diaLog时，重置表单验证和数据
      this.$refs.addFormRef.resetFields();
    },
    // 监听用户点击表单确认事件，触发预校验
    addUser(){
      console.log(this.$refs);
      // 通过ref选中form表单实例，调用validate方法对表单进行一次校验
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid)return this.$message.error('格式错误')
        // 发起添加用户的网络请求
        const {data:res} = await this.$axios.post('users',{
            username:this.formData.username,
            password:this.formData.password,
            email:this.formData.email,
            mobile:this.formData.tel
          }
        )
        // 判断请求结果是否失败
        if(res.meta.status!==201)return this.$message.error(res.meta.msg)
        // 提示请求成功
        this.$message.success(res.meta.msg);
        // 重新获取最新的用户列表
        this.getUserlist();
        // 关闭diaLog消息框
        this.addDialogVisible = false;
      })
    },
    // 监听修改用户信息
    addDialogVisibleEdit(row){
      this.editFormData.id = row.id;
      this.isdialogVisible = true;
      this.editFormData.username = row.username;
    },
    // 确认时对表单进行预校验
    editUser(){
      this.$refs.editForm.validate(async valid=>{
        if(!valid) return this.$message.error('格式错误')
        const {data:res} = await this.$axios.put(`users/${this.editFormData.id}`,{
          id:this.editFormData.id,
          email:this.editFormData.email,
          mobile:this.editFormData.tel
        });
        if(res.meta.status!==200){
          return this.$message.error(res.meta.msg);
        }
        // 提示修改成功
        this.$message.success(res.meta.msg);
        // 重新获取最新的用户列表
        this.getUserlist();
        // 关闭diaLog消息框
        this.isdialogVisible = false;
      })
    },
    // 监听删除用户，提示是否确认删除
    delUser(user) {
        this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$axios.delete(`users/${user.id}`)
          if(res.meta.status!==200) return this.$message.error(res.meta.msg);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUserlist();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      // 监听用户单击分配角色弹出dialog对话框并获取角色列表
      async setRole(user){
        this.setRoleDialogVisible = true;
        this.currentUser = user;
        // 获取角色列表
        const {data:res} = await this.$axios.get(`roles`);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.rolesList = res.data
      },
      // 监听用户在分配角色对话框中点击确认
      async setRoleCommit(){
        const {data:res} = await this.$axios.put(`users/${this.currentUser.id}/role`,{
          rid:this.currentRoleId
        });
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)

        this.$message.success(res.meta.msg);
        this.setRoleDialogVisible = false;
        this.getUserlist();
        console.log(res);
      },
      // 监听用户关闭对话框
      setRoleDialogClose(){
        this.currentRoleId = '';
      }
  },
  created() {
    // 初始化后获取用户列表
    this.getUserlist();
  },
  
};
</script>

<style lang="less" scoped>

</style>